package me.zhengjie.modules.account.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.account.domain.AccountAa03;
import me.zhengjie.modules.account.domain.AccountAc50;
import me.zhengjie.modules.account.factory.entity.BaseUnitApprove;
import me.zhengjie.modules.account.factory.service.AccountComputer;
import me.zhengjie.modules.account.factory.vo.CheckPersonFees;
import me.zhengjie.modules.account.mapper.AccountAa03Mapper;
import me.zhengjie.modules.account.mapper.AccountAc08Mapper;
import me.zhengjie.modules.account.mapper.AccountAc50Mapper;
import me.zhengjie.modules.account.mapper.AccountAc50a5Mapper;
import me.zhengjie.modules.account.service.AccountAa03Service;
import me.zhengjie.modules.account.service.AccountAc50Service;
import me.zhengjie.modules.basic.domain.BasicAc02;
import me.zhengjie.modules.basic.domain.BasicAe03;
import me.zhengjie.modules.basic.mapper.BasicAc02Mapper;
import me.zhengjie.modules.basic.mapper.BasicAe03Mapper;
import me.zhengjie.modules.basic.service.BasicAc02Service;
import me.zhengjie.modules.logs.domain.BusinessLog;
import me.zhengjie.modules.logs.service.BusinessLogService;
import me.zhengjie.modules.sequence.service.SequenceService;
import me.zhengjie.tool.DateUtil;
import me.zhengjie.tool.ListUtil;
import me.zhengjie.tool.MyMap;
import me.zhengjie.tool.ValidateUtil;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.vo.Constant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional
public class AccountAc50ServiceImpl extends ServiceImpl<AccountAc50Mapper, AccountAc50> implements AccountAc50Service {

    @Resource
    private final AccountAc50Mapper  accountAc50Mapper;
    @Resource
    private final SequenceService sequenceService;
    @Resource
    private final BasicAe03Mapper basicAe03Mapper;
    @Resource
    private final AccountAc08Mapper accountAc08Mapper;
    @Resource
    BasicAc02Mapper basicAc02Mapper;
    @Resource
    BasicAc02Service basicAc02Service;
    @Resource
    BusinessLogService businessLogService;



    public Map getAc50List(Map param) {
        ValidateUtil.isEmptyThrowException(param.get("aac001"),"个人编号");
        Map result = Maps.newHashMap();
        BigDecimal jgzqyje = BigDecimal.ZERO; // 机关转企业职工养老保险金额
        BigDecimal jgznjje = BigDecimal.ZERO; // 转职业年金（改革前试点划转金额）
        BigDecimal aae240 = BigDecimal.ZERO; // 总金额
        param.put("aae100", Constant.AAE100_1_YX);
        if (!ValidateUtil.isEmpty(param.get("accountList"))) {
            List<Map> accountList = JSONObject.parseArray(param.get("accountList").toString(),Map.class) ;
            param.put("aaz116s",ListUtil.listMap2ListString(accountList,"aaz116"));
        }
        List<AccountAc50> ac50List = accountAc50Mapper.getAc50List(param);
        if (!ValidateUtil.isEmpty(ac50List)) {
            // 汇总金额
            jgzqyje = ValidateUtil.isEmpty(ac50List.stream().filter(item->(Constant.AAC062_1_RYXCB.equals(item.getAac062()))))
                    ? BigDecimal.ZERO: ac50List.stream().filter(item->(Constant.AAC062_1_RYXCB.equals(item.getAac062())))
                    .map(m -> ValidateUtil.isEmpty(m.getAae240()) ? BigDecimal.ZERO : m.getAae240()).reduce(BigDecimal.ZERO, BigDecimal::add);
            jgznjje = ValidateUtil.isEmpty(ac50List.stream().filter(item->(Constant.AAC062_9_QT.equals(item.getAac062()))))
                    ? BigDecimal.ZERO: ac50List.stream().filter(item->(Constant.AAC062_9_QT.equals(item.getAac062())))
                    .map(m -> ValidateUtil.isEmpty(m.getAae240()) ? BigDecimal.ZERO : m.getAae240()).reduce(BigDecimal.ZERO, BigDecimal::add);
            aae240 = ac50List.stream().map(m -> ValidateUtil.isEmpty(m.getAae240()) ? BigDecimal.ZERO : m.getAae240())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        // 查询银行信息
        Map queryMap = Maps.newHashMap();
        queryMap.put("aaz010", param.get("aac001"));
        queryMap.put("aaa028", Constant.AAA028_20_RY);

        List<BasicAe03> ae03s = basicAe03Mapper.getAe03List(queryMap);
        if (!ValidateUtil.isEmpty(ae03s)) {
            result.put("ae03s",ae03s);
        } else {
            throw new RuntimeException("未查询到该人员银行信息，请先去维护!");
        }
        result.put("ac50",ac50List);
        result.put("jgzqyje",jgzqyje);
        result.put("jgznjje",jgznjje);
        result.put("aae240",aae240);
        return result;
    }

    @Override
    public Map getAc50AllList(Map param) {
        ValidateUtil.isEmptyThrowException(param.get("aac001"),"个人编号");
        Map result = Maps.newHashMap();
        param.put("aac062", param.get("aac062"));
        param.put("aaz159", param.get("aaz159"));
        List<AccountAc50> ac50List = accountAc50Mapper.getAc50List(param);
        result.put("ac50",ac50List);
        return result;
    }

    @Override
    public Map saveAc50(MyMap param) throws Exception {
        ValidateUtil.isEmptyThrowException(param.get("aac001"),"个人编号");
        if (ValidateUtil.isEmpty(param.get("accountList"))) {
            throw new RuntimeException("人员退保账户列表参数为空");
        }
        List<AccountAc50> oldAccountList = (List<AccountAc50>) param.get("oldAccountList");

        BusinessLog businessLog = BusinessLog.singleLog(param);
        businessLogService.save(businessLog);


        // 生成单据
        //银行信息
//        Map queryMap = Maps.newHashMap();
//        queryMap.put("aaz010", param.get("aac001"));
//        queryMap.put("aaa028", Constant.AAA028_20_RY);
//
//        List<BasicAe03> ae03s = basicAe03Mapper.getAe03List(queryMap);
//        if (ValidateUtil.isEmpty(ae03s)) {
//            throw new RuntimeException("未查询到r的银行信息，请先维护");
//        }


        List<Map> ae03s = new ArrayList<>();
        ae03s.add(param);
        BaseUnitApprove checkApprove = new BaseUnitApprove(sequenceService);
        param.put("aae734",param.get("aac003"));
        checkApprove.init(param); // 初始化数据
        checkApprove.setCollectBillBankList(ae03s); // 组装银行信息
        checkApprove.createFinancialDocuments();// 组装单据信息
        checkApprove.createAccount();// 组装账户信息

        // 保存
        // 插入ad01
        List<Map> documentList = checkApprove.getDocumentList();
        accountAc08Mapper.batchInsertAd01(documentList);

        // 更新账户为无效
        for (Map item: checkApprove.getAccountList()) {
            List<Map> updateList = new ArrayList<>();
            updateList.add(item);
            accountAc50Mapper.updateBatchAc50(updateList);
        }

        // 备份数据
        List<Map> oldAccountListbak = ListUtil.convertListEntity2ListMap(oldAccountList);
        List<String> aae116s = ListUtil.listMap2ListString(checkApprove.getAccountList(),"aaz116");
        oldAccountListbak = oldAccountListbak.stream().filter(item ->(aae116s.contains(item.get("aaz116").toString()))).collect(Collectors.toList());
        if (!ValidateUtil.isEmpty(oldAccountListbak)) {
            oldAccountListbak.forEach(item ->{
                item.put("aaz002",param.getAsString("aaz002"));
            });
        }
        for (Map item: oldAccountListbak) {
            List<Map> insertList = new ArrayList<>();
            insertList.add(item);
            accountAc50Mapper.batchInsertAc50Z1(insertList);
        }

        // 更新参保关系为终止参保
        if (oldAccountList.size() == checkApprove.getAccountList().size()) {
            for (AccountAc50 item:oldAccountList) {
                BasicAc02 params = new BasicAc02();
                params.setAaz159(item.getAaz159());
                BasicAc02 basicAc02 =  basicAc02Mapper.selectByAaz159(params);
                basicAc02.setAae011(SecurityUtils.getCurrentUsername());
                basicAc02.setAae036(DateUtil.getStringCurDateTime());
                basicAc02.setAac008(Constant.AAC008_4_ZZCB);
                basicAc02.setAae042(DateUtil.getCurrentTime());
                basicAc02.setAac031(Constant.AAC031_3_ZZJF);
                basicAc02.setAaz159(item.getAaz159());
                basicAc02Mapper.updateByAaz159(basicAc02);
            }
        }
        return null;
    }
}
